package system;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class TestSystem {
    private static List<Teacher> teachers = new ArrayList<>();
    private static List<Student> students = new ArrayList<>();
    private static List<Course> courses = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        initTestData();
        showMainMenu();
    }

    private static void initTestData() {
        // 初始化教师
        Teacher teacher1 = new Teacher("T001", "张教授", "男");
        Teacher teacher2 = new Teacher("T002", "李教授", "女");
        Teacher teacher3 = new Teacher("T003", "王教授", "男");
        Teacher teacher4 = new Teacher("T004", "陈教授", "女");
        teachers.add(teacher1);
        teachers.add(teacher2);
        teachers.add(teacher3);
        teachers.add(teacher4);

        // 初始化课程 - 包含学分信息
        Course course1 = new Course("C001", "Java编程基础", "教学楼A101", "周一 8:00-10:00", 30, 3);
        Course course2 = new Course("C002", "数据结构与算法", "教学楼B201", "周三 10:00-12:00", 25, 4);
        Course course3 = new Course("C003", "数据库原理", "实验楼301", "周五 14:00-16:00", 20, 3);
        Course course4 = new Course("C004", "操作系统", "教学楼A102", "周一 10:00-12:00", 35, 4);
        Course course5 = new Course("C005", "计算机网络", "教学楼C301", "周二 14:00-16:00", 28, 3);
        Course course6 = new Course("C006", "软件工程", "教学楼B105", "周四 8:00-10:00", 32, 2);
        courses.add(course1);
        courses.add(course2);
        courses.add(course3);
        courses.add(course4);
        courses.add(course5);
        courses.add(course6);

        // 教师开课
        teacher1.assignCourse(course1);
        teacher2.assignCourse(course2);
        teacher3.assignCourse(course3);
        teacher1.assignCourse(course4);
        teacher4.assignCourse(course5);
        teacher2.assignCourse(course6);

        // 初始化学生
        Student student1 = new Student("S001", "王小明", "男");
        Student student2 = new Student("S002", "刘小红", "女");
        Student student3 = new Student("S003", "李华", "男");
        Student student4 = new Student("S004", "张伟", "男");
        Student student5 = new Student("S005", "赵丽", "女");
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);
        students.add(student5);

        // 为部分学生预选一些课程
        student1.selectCourse(course1);
        student1.selectCourse(course5);
        student2.selectCourse(course2);
        student3.selectCourse(course3);
        student4.selectCourse(course1);
        student4.selectCourse(course6);
    }

    private static void showMainMenu() {
        while (true) {
            System.out.println("\n🎓 ====== 学生选课系统 ====== 🎓");
            System.out.println("1. 📝 教师开课");
            System.out.println("2. ✅ 学生选课");
            System.out.println("3. ❌ 学生退课");
            System.out.println("4. 📚 查看学生课表");
            System.out.println("5. 📋 查看所有课程");
            System.out.println("6. 👥 查看所有学生");
            System.out.println("7. 🔍 搜索课程");
            System.out.println("8. 📊 系统统计");
            System.out.println("9. 🚪 退出系统");
            System.out.print("请选择操作（1-9）: ");

            int choice = getIntInput();

            switch (choice) {
                case 1:
                    teacherOpenCourse();
                    break;
                case 2:
                    studentSelectCourse();
                    break;
                case 3:
                    studentDropCourse();
                    break;
                case 4:
                    viewStudentSchedule();
                    break;
                case 5:
                    viewAllCourses();
                    break;
                case 6:
                    viewAllStudents();
                    break;
                case 7:
                    searchCourses();
                    break;
                case 8:
                    showSystemStatistics();
                    break;
                case 9:
                    System.out.println("感谢使用选课系统，再见！👋");
                    return;
                default:
                    System.out.println("❌ 输入错误，请重新选择！");
            }
        }
    }

    private static void teacherOpenCourse() {
        System.out.println("\n📝 === 教师开课 ===");

        // 显示所有教师
        System.out.println("可选教师：");
        for (int i = 0; i < teachers.size(); i++) {
            Teacher teacher = teachers.get(i);
            System.out.println((i + 1) + ". " + teacher.getName() + " (" + teacher.getId() + ")");
        }

        System.out.print("选择教师编号: ");
        int teacherIndex = getIntInput() - 1;

        if (teacherIndex < 0 || teacherIndex >= teachers.size()) {
            System.out.println("❌ 教师选择错误！");
            return;
        }

        Teacher selectedTeacher = teachers.get(teacherIndex);

        // 输入课程信息
        System.out.print("输入课程编号: ");
        String courseId = scanner.nextLine();

        // 检查课程编号是否已存在
        for (Course course : courses) {
            if (course.getCourseId().equals(courseId)) {
                System.out.println("❌ 课程编号已存在，请使用其他编号！");
                return;
            }
        }

        System.out.print("输入课程名称: ");
        String courseName = scanner.nextLine();
        System.out.print("输入上课地点: ");
        String location = scanner.nextLine();
        System.out.print("输入上课时间: ");
        String time = scanner.nextLine();
        System.out.print("输入课程容量: ");
        int capacity = getIntInput();
        System.out.print("输入课程学分: ");
        int credits = getIntInput();

        // 创建课程并分配
        Course newCourse = new Course(courseId, courseName, location, time, capacity, credits);
        selectedTeacher.assignCourse(newCourse);
        courses.add(newCourse);

        System.out.println("🎉 开课成功！");
        System.out.println("📋 课程信息：");
        System.out.println("  课程名称: " + courseName);
        System.out.println("  授课教师: " + selectedTeacher.getName());
        System.out.println("  上课地点: " + location);
        System.out.println("  上课时间: " + time);
        System.out.println("  课程容量: " + capacity);
        System.out.println("  课程学分: " + credits);
    }

    private static void studentSelectCourse() {
        System.out.println("\n✅ === 学生选课 ===");

        Student student = selectStudent();
        if (student == null) return;

        // 显示学生当前选课情况
        System.out.println("\n📊 " + student.getName() + " 当前选课情况：");
        System.out.println("已选课程数: " + student.getSelectedCourses().size() + " | 总学分: " + student.getTotalCredits());

        // 显示可选课程的详细信息
        System.out.println("\n📋 可选课程列表：");
        System.out.println("=".repeat(120));

        int availableCount = 0;
        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);

            // 跳过已经选择的课程
            if (student.hasCourse(course.getCourseId())) {
                continue;
            }

            availableCount++;
            System.out.println(availableCount + ". " + course.getCourseDetail());
            System.out.println("-".repeat(120));
        }

        if (availableCount == 0) {
            System.out.println("❌ 没有可选课程了！");
            return;
        }

        System.out.print("请选择课程编号（输入0返回主菜单）: ");
        int courseChoice = getIntInput();

        if (courseChoice == 0) return;

        if (courseChoice < 1 || courseChoice > availableCount) {
            System.out.println("❌ 课程选择错误！");
            return;
        }

        // 找到对应的课程
        Course selectedCourse = null;
        int currentIndex = 0;
        for (Course course : courses) {
            if (!student.hasCourse(course.getCourseId())) {
                currentIndex++;
                if (currentIndex == courseChoice) {
                    selectedCourse = course;
                    break;
                }
            }
        }

        if (selectedCourse == null) {
            System.out.println("❌ 课程选择错误！");
            return;
        }

        // 执行选课
        if (student.selectCourse(selectedCourse)) {
            System.out.println("\n🎉 选课成功！");
            System.out.println("✅ " + student.getName() + " 成功选择 " + selectedCourse.getCourseName());
            System.out.println("📅 上课时间：" + selectedCourse.getTime());
            System.out.println("📍 上课地点：" + selectedCourse.getLocation());
            System.out.println("👨‍🏫 授课教师：" +
                    (selectedCourse.getTeacher() != null ? selectedCourse.getTeacher().getName() : "未分配"));
            System.out.println("🎓 课程学分：" + selectedCourse.getCredits());

            // 显示更新后的课表
            System.out.println("\n📊 当前课表：");
            student.printCourseSchedule();
        }
    }

    private static void studentDropCourse() {
        System.out.println("\n❌ === 学生退课 ===");
        Student student = selectStudent();
        if (student == null) return;

        if (student.getSelectedCourses().isEmpty()) {
            System.out.println("❌ 该学生未选任何课程！");
            return;
        }

        System.out.println("\n📚 " + student.getName() + " 的已选课程列表：");
        student.printCourseSchedule();

        System.out.print("请输入要退课的课程编号: ");
        String courseId = scanner.nextLine().trim();

        // 检查学生是否选了这门课
        if (!student.hasCourse(courseId)) {
            System.out.println("❌ 该学生未选择此课程！");
            return;
        }

        // 找到课程信息用于显示
        Course targetCourse = null;
        for (Course course : student.getSelectedCourses()) {
            if (course.getCourseId().equals(courseId)) {
                targetCourse = course;
                break;
            }
        }

        if (student.dropCourse(courseId)) {
            System.out.println("🎉 退课成功！");
            System.out.println("❌ " + student.getName() + " 已退选 " + targetCourse.getCourseName());
            System.out.println("📊 当前总学分: " + student.getTotalCredits());
        } else {
            System.out.println("❌ 退课失败！");
        }
    }

    private static void viewStudentSchedule() {
        System.out.println("\n📚 === 查看学生课表 ===");

        Student student = selectStudent();
        if (student == null) return;

        student.printCourseSchedule();
    }

    private static void viewAllCourses() {
        System.out.println("\n📋 === 所有课程信息 ===");
        if (courses.isEmpty()) {
            System.out.println("暂无课程");
            return;
        }

        System.out.println("共 " + courses.size() + " 门课程：");
        System.out.println("=".repeat(120));

        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);
            System.out.println((i + 1) + ". " + course.getCourseDetail());
            System.out.println("-".repeat(120));
        }
    }

    private static void viewAllStudents() {
        System.out.println("\n👥 === 所有学生信息 ===");
        if (students.isEmpty()) {
            System.out.println("暂无学生");
            return;
        }

        System.out.println("共 " + students.size() + " 名学生：");
        System.out.println("=".repeat(80));

        for (Student student : students) {
            System.out.println("学号: " + student.getId() + " | 姓名: " + student.getName() + " | 性别: " + student.getGender());
            System.out.println("已选课程数: " + student.getSelectedCourses().size() + " | 总学分: " + student.getTotalCredits());
            if (!student.getSelectedCourses().isEmpty()) {
                System.out.print("已选课程: ");
                for (Course course : student.getSelectedCourses()) {
                    System.out.print(course.getCourseName() + "(" + course.getCredits() + "学分) ");
                }
                System.out.println();
            } else {
                System.out.println("未选任何课程");
            }
            System.out.println("-".repeat(80));
        }
    }

    private static void searchCourses() {
        System.out.println("\n🔍 === 搜索课程 ===");
        System.out.println("1. 按课程名称搜索");
        System.out.println("2. 按教师姓名搜索");
        System.out.println("3. 按上课地点搜索");
        System.out.print("请选择搜索方式（1-3）: ");

        int searchType = getIntInput();
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入搜索关键词: ");
        String keyword = scanner.nextLine().toLowerCase();

        System.out.println("\n📋 搜索结果：");
        System.out.println("=".repeat(120));

        int resultCount = 0;
        for (Course course : courses) {
            boolean match = false;

            switch (searchType) {
                case 1:
                    match = course.getCourseName().toLowerCase().contains(keyword);
                    break;
                case 2:
                    if (course.getTeacher() != null) {
                        match = course.getTeacher().getName().toLowerCase().contains(keyword);
                    }
                    break;
                case 3:
                    match = course.getLocation().toLowerCase().contains(keyword);
                    break;
                default:
                    System.out.println("❌ 搜索方式选择错误！");
                    return;
            }

            if (match) {
                resultCount++;
                System.out.println(resultCount + ". " + course.getCourseDetail());
                System.out.println("-".repeat(120));
            }
        }

        if (resultCount == 0) {
            System.out.println("❌ 未找到相关课程！");
        } else {
            System.out.println("共找到 " + resultCount + " 门相关课程");
        }
    }

    private static void showSystemStatistics() {
        System.out.println("\n📊 === 系统统计信息 ===");
        System.out.println("=".repeat(50));

        // 课程统计
        int totalCapacity = 0;
        int totalEnrolled = 0;
        for (Course course : courses) {
            totalCapacity += course.getCapacity();
            totalEnrolled += course.getEnrolledCount();
        }

        System.out.println("📋 课程统计:");
        System.out.println("   总课程数: " + courses.size());
        System.out.println("   总容量: " + totalCapacity + " 人");
        System.out.println("   已选人数: " + totalEnrolled + " 人");
        System.out.println("   选课率: " + String.format("%.2f", (double) totalEnrolled / totalCapacity * 100) + "%");

        // 学生统计
        int studentsWithCourses = 0;
        int maxCredits = 0;
        Student topStudent = null;

        for (Student student : students) {
            if (!student.getSelectedCourses().isEmpty()) {
                studentsWithCourses++;
            }
            if (student.getTotalCredits() > maxCredits) {
                maxCredits = student.getTotalCredits();
                topStudent = student;
            }
        }

        System.out.println("\n👥 学生统计:");
        System.out.println("   总学生数: " + students.size());
        System.out.println("   已选课学生: " + studentsWithCourses + " 人");
        System.out.println("   选课率: " + String.format("%.2f", (double) studentsWithCourses / students.size() * 100) + "%");

        if (topStudent != null) {
            System.out.println("   最高学分: " + maxCredits + " 分 (" + topStudent.getName() + ")");
        }

        // 教师统计
        System.out.println("\n👨‍🏫 教师统计:");
        System.out.println("   总教师数: " + teachers.size());
        int teachingTeachers = 0;
        for (Teacher teacher : teachers) {
            if (teacher.getTeachingCourse() != null) {
                teachingTeachers++;
            }
        }
        System.out.println("   开课教师: " + teachingTeachers + " 人");

        System.out.println("=".repeat(50));
    }

    // 选择学生的辅助方法
    private static Student selectStudent() {
        System.out.println("\n选择学生：");
        for (int i = 0; i < students.size(); i++) {
            Student student = students.get(i);
            String courseInfo = student.getSelectedCourses().isEmpty() ?
                    "未选课" : student.getSelectedCourses().size() + "门课 (" + student.getTotalCredits() + "学分)";
            System.out.println((i + 1) + ". " + student.getName() + " (" + student.getId() + ") - " + courseInfo);
        }

        System.out.print("选择学生编号（输入0返回）: ");
        int studentIndex = getIntInput() - 1;

        if (studentIndex == -1) {
            return null;
        }

        if (studentIndex < 0 || studentIndex >= students.size()) {
            System.out.println("❌ 学生选择错误！");
            return null;
        }

        return students.get(studentIndex);
    }

    // 输入验证方法
    private static int getIntInput() {
        while (true) {
            try {
                int input = scanner.nextInt();
                scanner.nextLine(); // 消耗换行符
                return input;
            } catch (Exception e) {
                System.out.print("❌ 输入错误，请输入数字: ");
                scanner.nextLine(); // 清除错误输入
            }
        }
    }
}